package DB.Controle;

import DB.DBManager;
import Model.Usuario;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author pgrabin
 */
public class ControllerControle {
   
    DBManager db;
    Connection conn;
    static ControllerControle uControl;

    public static ControllerControle getInstance() {
        if (uControl == null) {
            uControl = new ControllerControle();
        }

        return uControl;
    }

    public ControllerControle(DBManager db, Connection conn) {
        this.db = db;
        this.conn = conn;
    }

    public ControllerControle() {
        db = DBManager.getInstance();
        conn = db.getConn();
    }
    
    /**
     * Insere ou atualiza um novo registro na tabela de controle, 
     * para salvar o login de algum usuario.
     * Salva o registro sempre com o ID 1. Se já houver, o existente é substituido.
     *
     * @param u
     * @return 1, se gravou. -1, se houve algum problema.
     */
    public long insert(Usuario u) {
        ResultSet generatedKeys = null;
        long idRetornado = -1;

        try {
            PreparedStatement ps = conn.prepareStatement("INSERT INTO " + ControleTable.TABLE_NAME + " VALUES (1, ?)", Statement.RETURN_GENERATED_KEYS);
            ps.setLong(1, u.getId());

            int affectedRows = ps.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("Creating user failed, no rows affected.");
            }
            generatedKeys = ps.getGeneratedKeys();
            if (generatedKeys.next()) {
                idRetornado = generatedKeys.getLong(1);
            } else {
                throw new SQLException("Creating user failed, no generated key obtained.");
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }

        return idRetornado;
    }
    
    /**
     * Busca na tabela de controle o registro informando o usuario salvo.
     *
     * @return Retorna o USUARIO com o ID informado
     */
    public int getID() {
        ResultSet rs;
        int userID = -1;

        try {
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + ControleTable.TABLE_NAME + " WHERE ID = 1");

            rs = ps.executeQuery();

            int id = 0;
            
            if (rs.next()) {
                id = rs.getInt(1);
                userID = rs.getInt(2);
            }
            
//            System.out.println(id + " --- " + userID);
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }

        return userID;
    }
    
    /**
     * Deleta da base o registro de controle do login salvo.
     *
     * @return 1, se funcionou.
     */
    public int delete() {
        int resultadoDelete = 0;

        try {
            PreparedStatement ps = conn.prepareStatement("DELETE FROM " + ControleTable.TABLE_NAME + " WHERE " + ControleTable.COLUMN_ID + " = 1");

            resultadoDelete = ps.executeUpdate();
            
            if (resultadoDelete == 0) {
                throw new SQLException("No record found for deletion");
            }

        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }

//        System.out.println("Usuario código " + id + " deletado!");
        return resultadoDelete;
    }
    
    public static void main(String args[]) {
        System.out.println("Iniciando...");

        ControllerControle cc = ControllerControle.getInstance();
        
        Usuario u = new Usuario(12121, "paulo", "plgrabin", "plgrabin", 1, null, null, null, null, null, null, null, null, null, null, null, null);
        System.out.println(u);
        
        cc.insert(u);
//        cc.delete();
        System.out.println(cc.getID());
    }
}
